using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;

namespace HomeLite.Controllers
{
    public class ServerController
    {        

        #region Singleton
        private static ServerController _instance;

        public static ServerController Instance
        {
            get
            {
                if (_instance == null) _instance = new ServerController();
                return _instance;
            }
        }
        #endregion

        #region Methods - Public

        static void ListenThreadJob()
        {
            HttpListener listener = new HttpListener();
            HttpListenerResponse response;
            HttpListenerRequest request;
            byte[] buffer;

            listener.Prefixes.Add("http://+:23284/play/");
            listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            listener.Start();

            while (true)
            {
                try
                {
                    HttpListenerContext ctx = listener.GetContext();
                    Console.WriteLine("Request from: " + ctx.Request.QueryString);
                    response = ctx.Response;
                    request = ctx.Request;

                    buffer = System.IO.File.ReadAllBytes(request.QueryString["file"]);

                    response.ContentType = "octet/stream";
                    response.ContentLength64 = buffer.Length;
                    response.OutputStream.Write(buffer, 0, buffer.Length);
                    response.OutputStream.Close();
                }
                catch (Exception ex)
                {
                }
            }
        }

        internal void Start()
        {
            ThreadStart job = new ThreadStart(ListenThreadJob);
            Thread thread = new Thread(job);
            thread.Start();
        }
        #endregion
    }
}
